<?php
//Code for updating mobile phones -
//update er_visit set mobile_no = (SELECT mobile_no FROM `er_client` where client_id = er_visit.client_id)

	$cmbIdType = $HTTP_POST_VARS['cmbIdType'];
	$txtNumber  = $HTTP_POST_VARS['txtNumber'];



	$idnumhyphen=explode('-',$txtNumber);
	$txtNumber = "";
	for ($i=0;$i<count($idnumhyphen);$i++)
	{
			$txtNumber=$txtNumber."". $idnumhyphen[$i];
	}

	$idnumspace=explode(' ',$txtNumber);
	$txtNumber = "";
	for ($i=0;$i<count($idnumspace);$i++)
	{
		$txtNumber=$txtNumber."". $idnumspace[$i];
	}

	$idnumdot=explode('.',$txtNumber);
	$txtNumber = "";
	for ($i=0;$i<count($idnumdot);$i++)
	{
		$txtNumber=$txtNumber."". $idnumdot[$i];
	}

	$idnumslash=explode('/',$txtNumber);
	$txtNumber = "";
	for ($i=0;$i<count($idnumslash);$i++)
	{
		$txtNumber=$txtNumber."". $idnumslash[$i];
	}

	$idnumbslash=explode('\\',$txtNumber);
	$txtNumber = "";
	for ($i=0;$i<count($idnumbslash);$i++)
	{
		$txtNumber=$txtNumber."". $idnumbslash[$i];
	}

	$first_visit = $HTTP_POST_VARS['first_visit'];

	$optGender  = $HTTP_POST_VARS['optGender'];

	$txtDateOfBirth=$HTTP_POST_VARS['txtDateOfBirth'];
	$cmbHousingType  = $HTTP_POST_VARS['cmbHousingType'];
	$cmbIncomeStatus  = $HTTP_POST_VARS['cmbIncomeStatus'];
	$txtGivenName = $HTTP_POST_VARS['txtGivenName'];
	$txtNationality = 'NULL';
	$txtPreferredLanguage  = 'NULL';
	$txtSurname = $HTTP_POST_VARS['txtSurname'];
	$txtOtherIdType = $HTTP_POST_VARS['txtOtherIdType'];
	$txtCurrentAddress = $HTTP_POST_VARS['txtCurrentAddress'];
	$txtCurrentPostCode  = $HTTP_POST_VARS['txtCurrentPostCode'];
	$txtCurrentState  = $HTTP_POST_VARS['txtCurrentState'];
	$txtCurrentSuburb = $HTTP_POST_VARS['txtCurrentSuburb'];
	$optErGiven = $HTTP_POST_VARS['optErGiven'];
	//$txtErReason = $HTTP_POST_VARS['txtErReason'];
	$txtInterviewer = $HTTP_POST_VARS['txtInterviewer'];
	$txtMobile = $HTTP_POST_VARS['txtMobile'];
	$txtVisitDate = $HTTP_POST_VARS['txtVisitDate'];
	$txtActionOther = $HTTP_POST_VARS['txtActionOther'];
	$txtReturnDate = $HTTP_POST_VARS['txtReturnDate'];
	//$txtDayBookColor  = $HTTP_POST_VARS['txtDayBookColor'];
	//$txtDayBookPageNo  = $HTTP_POST_VARS['txtDayBookPageNo'];

	$txtDayBookColor  = "";
	$txtDayBookPageNo  = 0;
	$txtChildren = $HTTP_POST_VARS['txtChildren'];
	$txtAdults  = $HTTP_POST_VARS['txtAdults'];
	$optClientSignature = $HTTP_POST_VARS['optClientSignature'];
	$txtOtherHousingType  = $HTTP_POST_VARS['txtOtherHousingType'];
	$txtOtherIncomeStatusType  = $HTTP_POST_VARS['txtOtherIncomeStatusType'];
	$txtOtherEr  = $HTTP_POST_VARS['txtOtherEr'];
	$txtOtherIncomeSourceType = $HTTP_POST_VARS['txtOtherIncomeSourceType'];
	$txtFortnightlyPayments  = $HTTP_POST_VARS['txtFortnightlyPayments'];
	$txtPhone = $HTTP_POST_VARS['txtPhone'];
	$txtCentreLinkAmount = $HTTP_POST_VARS['txtCentreLinkAmount'];
	$cmbSite = $HTTP_POST_VARS['cmbSite'];
	$cmbAgency  = $HTTP_POST_VARS['cmbAgency'];
	$txtVisitRecordedDate  = $HTTP_POST_VARS['txtVisitRecordedDate'];
	$payment1  = $HTTP_POST_VARS['payment1'];
	$payment2  = $HTTP_POST_VARS['payment2'];
	$payment3  = $HTTP_POST_VARS['payment3'];
	$payment4  = $HTTP_POST_VARS['payment4'];
	$payment5  = $HTTP_POST_VARS['payment5'];
	$txtErAmountRecieptNo = $HTTP_POST_VARS['txtErAmountRecieptNo'];
	$txtReasonChequePayment = $HTTP_POST_VARS['txtReasonChequePayment']."";
	$txtChequePayee = $HTTP_POST_VARS['txtChequePayee']."";
	$txtOtherPaymentType   = $HTTP_POST_VARS['txtOtherPaymentType']."";
	$extraFoodParcels = $HTTP_POST_VARS['extraFoodParcels']."";

	$referred_internal = $HTTP_POST_VARS['referred_internal'];
	$referred_external = $HTTP_POST_VARS['referred_external'];


	$txtCommentsDateTime = NULL;
	$txtCommentsDateTime  = date("d/m/Y");
	if (isset($HTTP_POST_VARS['cmbRank'])) {
		$cmbRank  = $HTTP_POST_VARS['cmbRank'];
	}

	if (isset($HTTP_POST_VARS['txtComments']))
	$txtComments = $HTTP_POST_VARS['txtComments'];
	$emergencyReliefs = $HTTP_POST_VARS['emergencyReliefs'];


	//Check the gender selected
	if($optGender=="Male")
	{
		$gender = "M";
	}
	elseif($optGender=="Female")
	{
		$gender = "F";
	}

	//Get combined date of birth

	$DOB =  $txtDateOfBirth;
	//$DOB = date("Y-m-d",$DOB); //format the date in yyyy-mm-dd format eg 2000/09/08

	$DbDOB=explode("/",$DOB);
	$dayDOB=$DbDOB[0];
	if (isset($DbDOB[1])) {
		$monthDOB=$DbDOB[1];
	}
	else {
		$monthDOB = null;
	}
	if (isset($DbDOB[2])) {
		$yearDOB=$DbDOB[2];
	}
	else {
		$yearDOB = null;
	}
	$DOB=$yearDOB."-".$monthDOB."-".$dayDOB;

	$current_date = date("Y-m-d");

	//Get selected housing type ID
	$housingID = getIdFromListBox("er_housing_type","Housing_Type",$cmbHousingType);
	$incomeStatusId = getIdFromListBox("er_income_status","Income_Status_Type",$cmbIncomeStatus);

	$identificationNo = getIdFromListBox("er_identification_type","identification_type", $cmbIdType);

	$agencyId = getIdFromListBox("er_agency","agency_name",$cmbAgency);


$queryClientTable = "INSERT INTO er_client
		(id_reference_no,
		surname,
		givenname,
		dob,
		nationality,
		gender,
		preferred_language,
		other_id_type_specified,
		first_visit,
		identification_no)
		VALUES (" .
		"'$txtNumber',
		'$txtSurname',
		'$txtGivenName',
		'$DOB',
		'$txtNationality',
		'$gender',
		'$txtPreferredLanguage',
		'$txtOtherIdType',
		'$first_visit',
		$identificationNo
		)";

	$results = r_db($queryClientTable);
	$queryClientId = "select last_insert_id()";
	$resultClientId = r_db($queryClientId);

	while ($row=mysql_fetch_array($resultClientId))
	{
		$clientId = $row[0];
	}


	//=====================INSERTION IN VISIT TABLE========================


	$housingId = getIdFromListBox("er_housing_type","Housing_Type",$cmbHousingType);

	$incomeStatusId = getIdFromListBox("er_income_status","Income_Status_Type",$cmbIncomeStatus);

	$agencyId = getIdFromListBox("er_agency","agency_name",$cmbAgency);

	$visitdate=explode("/",$txtVisitDate);
	$visitdateday=$visitdate[0];
	$visitdatemonth=$visitdate[1];
	$visitdateyear=$visitdate[2];
	$txtVisitDate=$visitdateyear."-".$visitdatemonth."-".$visitdateday;

$queryVisit = "
					INSERT INTO er_visit
			(
visit_recorded_date ,
visit_date,
address,
postcode,
state,
suburb,
er_given,
interviewer,
day_book_colour,
day_book_page_no,
no_children_assistted,
no_adults_assistted,
site_visited_id,
client_id,
client_signature,
housing_type_id,
other_housing_type,
income_status_id,
other_income_status,
other_ER,
other_income_source,
agency_id,
rent_paid_pf,
phone_no,
er_amount_receipt_no,
reason_cheque_payment,
cheque_payee,
other_payment_type,
mobile_no,
extra_food_parcels,
referred_internal,
referred_external,
action_taken,
return_date
)

					VALUES (now(),
					'$txtVisitDate',
					'$txtCurrentAddress',
					$txtCurrentPostCode,
					'$txtCurrentState',
					'$txtCurrentSuburb',
					'$optErGiven',
					'$txtInterviewer',
					'$txtDayBookColor',
					$txtDayBookPageNo,
					$txtChildren,
					$txtAdults,
					$cmbSite,
					'$clientId',
					'$optClientSignature',
					$housingId,
					'$txtOtherHousingType',
					$incomeStatusId,
					'$txtOtherIncomeStatusType',
					'$txtOtherEr',
					'$txtOtherIncomeSourceType',
					$agencyId,
					$txtFortnightlyPayments,
					'$txtPhone',
					'$txtErAmountRecieptNo',
					'$txtReasonChequePayment',
					'$txtChequePayee',
					'$txtOtherPaymentType',
					'$txtMobile',
					'$extraFoodParcels',
					'$referred_internal',
					'$referred_external',
					'$txtActionOther',
					'$txtReturnDate'
					)";

//echo "<\br>". $queryVisit;

	$resultVisit = r_db($queryVisit);
	mysql_affected_rows();
	$visitId = mysql_insert_id();

	$q = "SELECT LAST_INSERT_ID()";

	$res = r_db($q);

	$r = mysql_fetch_array($res);


//===========================PAYMENT TYPES====================================================
$queryPayment = "SELECT * FROM er_payment";
$resultPayment = r_db($queryPayment);
//reset($payment);

while ($rowPayment = mysql_fetch_array($resultPayment))
{
	if (!empty($_POST['payment'.$rowPayment[0]])) {
		$q = "INSERT INTO er_payment_on_visit (payment_id, visit_id, payment_amount) VALUES ($rowPayment[0], $visitId, {$_POST['payment'.$rowPayment[0]]})";
		r_db($q);
	}
}

//==============================CLIENT INCOMES===================================================

$amount = $HTTP_POST_VARS['amount'];
$whenDue = $HTTP_POST_VARS['whenDue'];
$incomes = $HTTP_POST_VARS['incomes'];

$whenDueAmerican = array();
$arrWhenDueEnglish = array();
for($i=0;$i<count($whenDue);$i++)
{
	if (!empty($whenDue[$i])) {
		$whenDueAmerican[$i]=$whenDue[$i];
		$day=substr($whenDueAmerican[$i],0,2);
		$month=substr($whenDueAmerican[$i],3,2);
		$year=substr($whenDueAmerican[$i],6,4);
		$whenDueEnglish=$year."-".$month."-".$day;
		array_push($arrWhenDueEnglish, $whenDueEnglish);
	}

}

insert_incomes($incomes,$visitId, $amount, $arrWhenDueEnglish);

function insert_incomes($incomes, $visitId, $amount, $whenDue)
{
   $query = "INSERT INTO er_client_income (income_id, visit_id, income_amount, when_due) VALUES";
   $i = 0;
   $selected = array();
   $previouslyRecord = null;

   reset($incomes);
   foreach ($incomes as $value)
   {
   	$incomeId = getIdFromListBox("er_income_source","income_type",$value);
   	if (count($selected) > 0) {
   		$foundRecord = array_search($incomeId, $selected, true);
   		if (is_int($foundRecord)) {
   			$previouslyRecord = $incomeId;
   		}
   	}
		if ($incomeId != 1 && $previouslyRecord != $incomeId) {
			if (!isset($whenDue[$i])) {
				$whenDue[$i] = null;
			}
			if (!isset($amount[$i])) {
				$amount[$i] = null;
			}
	    $query .=  " ($incomeId, $visitId, $amount[$i], '$whenDue[$i]')" . ",";
	    $i++;
	  }
	  $selected[] = $incomeId;
   }
   $query = substr($query, 0, -1);
   mysql_query($query);
}

//========================================================================
$txtCommentsDateTime=explode("/",$txtCommentsDateTime);
if (isset($txtCommentsDateTime))
{
$day=$txtCommentsDateTime[0];
$month=$txtCommentsDateTime[1];
$year=$txtCommentsDateTime[2];
$txtCommentsDateTime=$year."-".$month."-".$day;
}
if (isset($txtComments))
{

	if($txtComments != null)
	{
		$queryComments = "INSERT INTO er_comments (comment,comment_datetime,rank, client_id)
						VALUES ('$txtComments', '$txtCommentsDateTime','$cmbRank', '$clientId')";

		r_db($queryComments);
	}

}

//========================================================================
//=============================releif on visit========================================
insert_reliefs($emergencyReliefs,$visitId);
function insert_reliefs($emergencyReliefs, $visitId)
{

	$query = "INSERT INTO er_relief_on_visit (visit_id, relief_id) VALUES";
	$i = 0;

	reset($emergencyReliefs);
	foreach ($emergencyReliefs as $check)
	{
		$query .= " ($visitId, $check),";
		$i++;
	}
	$query = substr($query, 0, -1);

	r_db($query);
}



//=============================ACTION TAKEN ADDED 7/11/2007=========================================


if (isset($HTTP_POST_VARS['actionTaken'])) {
	$actionTaken = $HTTP_POST_VARS['actionTaken'];
	insert_action($actionTaken, $visitId);
}

function insert_action($actionTaken, $visitId)
{

	$query = "INSERT INTO er_action_on_visit (visit_id, action_id) VALUES";
	$i = 0;

	reset($actionTaken);
	foreach ($actionTaken as $check)
	{
		$query .= " ($visitId, $check),";
		$i++;
	}
	$query = substr($query, 0, -1);

	mysql_query($query);
}


echo "<p>New client saved successfully.</p>";
$ClientID=$clientId;

$visit_id = $visitId;
$client_id = $clientId;


include("page2.php");

?>



